import { systems, routes, type BreadcrumbSystemType, getMenus, menus } from '@/breadcrumb'
import { CommonSystemName } from '@/breadcrumb/breadcrumbs'
import { defineStore } from 'pinia'

const id = 'pinia-store-user'

const store = defineStore(id, {
  state: () => ({
    root: false,
    token: '',
    username: '',
    avatar: '',
    permissions: [] as string[],
    collapse: false,
    // system: CommonSystemName as BreadcrumbSystemType,
    // menu: HomeName as string,
    system: CommonSystemName as BreadcrumbSystemType,
    menu: '',
    tab: '' as string,
    tabs: [] as BusinessTabItem[],
    breadcrumbs: [] as string[]
  }),
  getters: {
    permissionSystems(state) {
      if (state.root) {
        return systems
      }
      return systems.filter((s) => state.permissions.includes(s.permission))
    },
    permissionSystemNames(): string[] {
      return this.permissionSystems.map((s) => s.name)
    },
    permissionMenus(state) {
      if (state.root) {
        return menus[state.system]
      }
      const t = getMenus(state.permissions)
      if (state.system in t) {
        return t[state.system]
      }
      return []
    },
    permissionRoutes(state) {
      if (state.root) {
        return routes
      }
      return routes.filter(
        (r) => r.meta?.permission && state.permissions.includes(r.meta.permission as string)
      )
    },
    permissionRouteNames(): string[] {
      return this.permissionRoutes.map((r) => r.name) as string[]
    }
  },
  actions: {
    tabToggle(item: Omit<BusinessTabItem, 'closable'>) {
      this.tab = item.path
      const tab = this.tabs.find((t) => t.path === item.path)
      if (!tab) {
        this.tabs.push({
          ...item,
          closable: false
        })
      }

      // 重新计算是否有关闭按钮
      this.tabs.forEach((t) => (t.closable = this.tabs.length > 1))
    },
    removeTab(path: string) {
      const index = this.tabs.findIndex((t) => t.path === path)
      if (index > -1) {
        this.tabs.splice(index, 1)

        // 重新计算是否有关闭按钮
        this.tabs.forEach((t) => (t.closable = this.tabs.length > 1))

        // 激活删除项临近的tab
        const active = this.tabs.find((t) => t.path === this.tab)
        if (active) {
          return
        }
        const activeIndex = index - 1
        if (activeIndex < 0) {
          return this.tabs[0].path
        }
        return this.tabs[activeIndex].path
      }
    }
  },
  persist: {
    key: id
    // 需要持久化存储的 key
    // paths: ['token', 'user', 'menuActive', 'tabs', 'layout', 'collapse']
  }
})

export default store
